import { Component, AfterViewInit, HostBinding } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    selector: 'app-index-widget',
    templateUrl: './index-widget.component.html',
    styleUrls: ['./index-widget.component.css']
})
export class IndexWidgetComponent implements AfterViewInit {
    @HostBinding('class.preview-widget-layout') cls = true;

    isStylesReady = false;

    themeName: string;

    themeSize: string;

    colorTheme: string;

    constructor(private router: Router) {
        const THEME_POSITION = 2;
        const COLOR_THEME_POSITION = 3;
        const urlParts = this.router.url.split('/');
        this.themeName = urlParts[THEME_POSITION];
        const tColorTheme = urlParts[COLOR_THEME_POSITION].split('-');
        if (tColorTheme.length > 1) {
            this.colorTheme = tColorTheme[0];
            this.themeSize = tColorTheme[1];
        } else {
            this.colorTheme = tColorTheme[0];
            this.themeSize = 'default';
        }
    }

    receiveMessage(e: any): void {
        if (e.data && e.data.name) {
            this.addHeadStyles(e.data.css);
            this.themeSize = e.data.themeSize;
        }
    }

    /**
     * 追加通过变量生成的样式
     * <style type="text/css" id="dynamic-styles">
     * </style>
     * @param css
     */
    addHeadStyles(css: string): void {
        const head = document.getElementsByTagName('head')[0];
        const style = document.createElement('style');
        const DYNAMIC_STYLES_ID = 'dynamic-styles';

        const dynamicStylesElement = document.getElementById(DYNAMIC_STYLES_ID);

        if (dynamicStylesElement) {
            dynamicStylesElement.parentNode.removeChild(dynamicStylesElement);
        }
        if (css) {
            style.type = 'text/css';
            style.id = DYNAMIC_STYLES_ID;
            style.appendChild(document.createTextNode(css));
            head.appendChild(style);
            // 当样式已经加载成功
            this.isStylesReady = true;
        }
    }

    private insterAfter(newElement, targetElement) {
        const parent = targetElement.parentNode;
        if (parent.lastChild === targetElement) {
            parent.appendChild(newElement);
        } else {
            parent.insertBefore(newElement, targetElement.nextSibling);
        }
    }

    /**
     * 添加link比追加css方式节省性能
     */
    private addHeadLinks(): void {
        if (this.colorTheme !== 'default' || this.themeSize !== 'default') {
            const head = document.getElementsByTagName('head')[0];
            const linkEl = document.createElement('link');
            const DYNAMIC_LINKS_ID = 'dynamic-links';
            // 应该不存在这种场景
            const dynamicLinksElement = document.getElementById(DYNAMIC_LINKS_ID);
            if (dynamicLinksElement) {
                dynamicLinksElement.parentNode.removeChild(dynamicLinksElement);
            }
            linkEl.rel = 'stylesheet';
            linkEl.id = DYNAMIC_LINKS_ID;
            linkEl.href = 'assets/themes/' + this.colorTheme + '/' + this.themeSize + '/farris-all.css';
            this.insterAfter(linkEl, head.querySelector('#farrisThemeLink'));
        }
    }

    ngAfterViewInit(): void {
        this.addHeadLinks();
        const messageListener = this.receiveMessage.bind(this);
        window.removeEventListener('message', messageListener);
        window.addEventListener('message', messageListener, false);
        window.parent.postMessage({ hideLoading: true }, window.parent.location.href);
    }
}
